var db        = exports;
var Mongolian = require("mongolian");
var eyes      = require('eyes');
var _         = require("./lib/underscore.js");
var crypto    = require('crypto');


// Config
var host            = "localhost";
var port            = 27017;
var databaseName    = "midgard";
var username        = "midgard";
var password        = "midgard";

// Set up server
var server          = new Mongolian(host+":"+port);
var dbc             = server.db(databaseName);
dbc.auth(username, password);

// Collections
db.projects  = dbc.collection("projects");
db.users     = dbc.collection("users");
db.events    = dbc.collection("events");

// Methods
db.getUser = function (data, callback) {
    var username    = data.user.name;
    var password    = data.user.password;
    var md5         = crypto.createHash('md5').update(password).digest("hex");

    db.users.findOne({ username: username, password: md5},
        function(err, user) {
            if (err) throw err;
            callback(err, user);
        }
    );
};

db.checkUsername = function (data, callback) {
    var username    = (data.user.name).toLowerCase();
    db.users.findOne({ username: username},
        function(err, user) {
            if (err) throw err;
            callback(err, user);
        }
    );
};


db.getUsers = function (data, callback) {
    // data is currently unused, but is there for lulz (or later)

    db.users.find(data).toArray(
        function(err, userList) {
            if (err) throw err;
            callback(userList);
        }
    );
};

db.editUser = function (data, callback) {
    var editId = data._id;
    delete data._id;
    if (data.level){ data.level = parseInt(data.level);}//Need to be Int32 in Db
    db.users.update({ _id:new Mongolian.ObjectId(editId) }, {$set: data },
        function (err, sucess) {
            if (err) throw err;
            callback(true);
        }
     );
};


db.userByName = function(name, cb) {
    var tokens = name.split(" ");
    var last = tokens.pop(); // "Jessheim"
    var first = tokens.shift(); // "Jon"
    var f = function(d) {return new RegExp(d)}
    
    db.users.findOne({firstname: f(first), lastname: f(last)}, function(err,obj) {
        if (err) throw err;
        var id = "FFFFUUUUUU";
        if (obj) id = obj._id.toString(); // if stuff is found, attach its id =)
        var o = {
            _id: id,
            name: name
        }
        cb(o);
    });
}

db.editProject = function (project, callback) {
    var editId = project._id;
    delete project._id;
    var tnow = Date.now();
    var lotion = parseInt(tnow/1000);
    project.dateModified = lotion;
    project.messageSent = false;
    eyes.inspect(project, "project [update variables]");
    db.projects.update({ _id:new Mongolian.ObjectId(editId) }, {$set: project },
        function (err, success) {
            if (err) throw err;
            if (callback) callback(err,success);
        }
    );
};

db.getProjects = function (data,tempClient) {
    var projectPhase    = data.phase;
    var year            = data.year;
    var month           = data.month;
    var container       = data.container;
    var start           = (new Date(year,month,1,0,0,0).valueOf() * 0.001)|0;
    var stop            = (new Date(year,parseInt(month)+1).valueOf() * 0.001)|0;
    var sort            = data.sort;
    var query           = {};
    query[sort.sortby]  = {$gte:start, $lt:stop};
    query["phase"]      = projectPhase

    //eyes.inspect(month, "month");
    //eyes.inspect(data, "db#getProjects data");
    //eyes.inspect(start, "db#getProjects start");
    //eyes.inspect(stop, "db#getProjects stop");

    db.projects.find(query
    ).sort(sort).forEach(function (project) {
        var pId = project._id.toString();
        tempClient.now.receiveProjects(project, container,pId);
    }, function(err) {
        if(err) throw err;
    });
};

db.getIdeas = function(data, cb) {
    // data = currently nothing, but possible add later
    db.projects.find({phase: 'idea'}
    ).toArray(function (err, ideas) {
        if (err) throw err;
        cb(ideas);
    });
};

db.updateIdeaPosition = function(ideaId,x,y) {
    db.projects.findOne({ _id: new Mongolian.ObjectId(ideaId) },
        function(err, idea) {
            if (err) throw err;
            idea.x=x;
            idea.y=y;
            db.projects.update({ _id: new Mongolian.ObjectId(ideaId) }, idea);
        }
    );
};

db.getProject = function (projectId, callback) {
    var _id = new Mongolian.ObjectId(projectId);
    db.projects.findOne({ _id: _id},
        function(err, project) {
            if (err) throw err;
            callback(project);
        }
    );
};

db.getUserById = function (userId, callback) {
    var _id = new Mongolian.ObjectId(userId);
    db.users.findOne({ _id: _id},
        function(err, project) {
            if (err) throw err;
            callback(err,project);
        }
    );
};


db.modifyProject = function(projectId, modifier) {
    db.getProject(projectId, function(proj) {
        modifier(proj); // !! ´modifier´ changes the proj object
        proj.dateModified = parseInt(Date.now() / 1000);
        eyes.inspect(proj.dateModified, 'dateModified [@modifyProject]');
        db.projects.update({ _id: new Mongolian.ObjectId(projectId) }, proj);
    });
}

db.getEvents = function (user,callback) {
    var userid          = 	user;
    db.events.find({userid: userid}
    ).sort({date:-1}
    ).toArray(function (err, events) {
        if (err) throw err;
            var length =  events.length
            console.log("Length:" + length);
            for(var i in events){
                events[i].date = dateToString(new Date(events[i].date*1000));
                console.log(events[i].date);
            };
        callback(events);
        }
    )
};
db.createEvent = function (event,callback){
    db.events.insert(event);
}

function dateToString(aDate){
    var dateString = aDate.getDate() + "."+(aDate.getMonth()+1) + "."+aDate.getFullYear();
    return dateString;
}